package com.beyond.trace.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.beyond.trace.config.AliyunSmsProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @ClassName: AliyunSmsService
 * @author: z越
 * @date: 2023/2/27  16:15
 * @description
 */
@Service
@RequiredArgsConstructor
public class AliyunSmsService {
    private final AliyunSmsProperties aliyunSmsProperties;
    public static final String ALARM_TEMPLATE_CODE = "{\"deviceType\":\"%s\", \"time\": \"%s\",\"alarmType\": \"%s\"}";
    //public static final String ALARM_TEMPLATE_CODE = "{\"deviceType\":\"%s\", \"time\": \"%s\",\"remark\": \"%s\"}";
    /**
     *  发送短信
     * @param phone  手机号, 多个用逗号隔开
     * @param templateParam  模板中所需要的参数
     */
    public boolean send(String phone ,String templateParam){
        DefaultProfile profile = DefaultProfile.getProfile(aliyunSmsProperties.getRegionId(),
                aliyunSmsProperties.getAccessKeyId(), aliyunSmsProperties.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        // 创建通用的请求对象
        CommonRequest request = new CommonRequest();
        // 指定请求方式
        request.setSysMethod(MethodType.POST);
        // 短信api的请求地址  固定
        request.setSysDomain(aliyunSmsProperties.getDomain());
        // 签名算法版本  固定
        request.setSysVersion("2017-05-25");
        // 请求 API 的名称
        request.setSysAction("SendSms");
        // 指定地域名称
        request.putQueryParameter("RegionId", aliyunSmsProperties.getRegionId());
        // 要给哪个手机号发送短信  指定手机号
        request.putQueryParameter("PhoneNumbers", phone);
        // 您的申请签名
        request.putQueryParameter("SignName", aliyunSmsProperties.getSignName());
        // 您申请的模板 code
        request.putQueryParameter("TemplateCode", aliyunSmsProperties.getTemplateCode());
        // 设置模板参数
        request.putQueryParameter("TemplateParam", templateParam);

        try {
            CommonResponse response = client.getCommonResponse(request);
            return response.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
